//获取应用实例
var app = getApp()
var countTimer, musicPlayCtx;
Page({
  data: {
    curQuestionIndex:1,
    isShowresult:false,
    // question:[
    //   {
    //     question:'今年什么时候立春？',
    //     answers: [
    //       {
    //         name: '3月份'
    //       }, {
    //         name: '4月份'
    //       }, {
    //         name: '5月份'
    //       }, {
    //         name: '6月份'
    //       }
    //     ]
    //   },
    // ]
  },
  onLoad: function (e) {
    var that = this;
    if(e&&e.type){
      that.setData({
        type: e.type
      })
    }
    if (e && e.from) {
      that.setData({
        from: e.from
      })
    }
    if (e && e.enterfrom) {
      var enterfrom = e.enterfrom == 'share' ? true : false;
      that.setData({
        enterfrom: enterfrom
      })
    }
  },
  onReady: function (e) {
    var that = this;
    that.audioTimeCtx = wx.createAudioContext('timeAudio');
    that.audioErrorCtx = wx.createAudioContext('errorAudio');
    that.audioRightCtx = wx.createAudioContext('rightAudio');
    that.endAudioCtx = wx.createAudioContext('endAudio');
    that.requestQuestions();
  },
  getAudio:function(){
    var that = this;
    console.log(that.audioTimeCtx);
    that.audioTimeCtx.play();
    that.setData({
      remainTime: app.globalData.answerTime ? app.globalData.answerTime:10,
      isQuestioning:true
    })
    that.countTime();
    // setTimeout(function () {
    //   that.countTime();
    // }, 800)
  },
  requestQuestions: function () {
    var that = this;
    var id = that.data.id;
    var type = that.data.type ? that.data.type : '';
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_subject_list',
        type: type
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          that.setData({
            reviveCard: res.data.data.reviveCard,
            allowCard: res.data.data.allowCard,
            question: res.data.data.list
          })
          if(res.data.data.remainder>0){
            that.getAudio();
            that.setData({
              noTimes:false
            })
          }else{
            that.setData({
              noTimes: true,
              isShowresult:true,
              modaltype:3,
              failTiptxt:"您的答题次数已用完~"
            })
          }
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
          that.setData({
            question:[]
          })
          setTimeout(function(){
            wx.navigateBack({
              delta:1
            })
          },1800)
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  onPullDownRefresh: function () {
    var that = this;
    that.requestQuestions();
    console.log("下拉刷新");
  },
  copy: function (e) {
    var that = this;
    var data = e.target.dataset.code;
    wx.setClipboardData({
      data: data,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            console.log(res.data) // data
            app.errorTip(that, '成功复制到剪贴板', 3000);
          }
        })
      }
    })
  },
  redbagWithdraw: function () {
    wx.navigateTo({
      url: '/pages/incomeWithdraw/incomeWithdraw'
    })
  },
  chooseAnswer:function(e){
    var that = this;
    var firstId = e.currentTarget.dataset.firstid;
    var questionId = e.currentTarget.dataset.quesid;
    var isRight = e.currentTarget.dataset.isright;
    var question = that.data.question;
    var curQuestionIndex = that.data.curQuestionIndex;
    console.log(firstId);
    console.log(questionId);
    for (var i = 0; i < question.length;i++){
     if(firstId == question[i].id){
       if (question[i].chooseAnswer != '') {
         return;
       }else{
         question[i].chooseAnswer = questionId;
         console.log(question[i].chooseAnswer);
       }
      }
    }
    that.audioTimeCtx.pause();
    that.audioTimeCtx.seek(0);
    if (isRight){
      that.audioRightCtx.play();
      setTimeout(function () {
        if (curQuestionIndex < question.length) {
          curQuestionIndex++;
          that.getAudio();
        }
        that.setData({
          curQuestionIndex: curQuestionIndex
        })
        var totalNum = question.length;
        var questionNum = 0;
        for (var i = 0; i < question.length; i++) {
          if (question[i].chooseAnswer != '') {
            questionNum++;
          }
        }
        console.log(totalNum + '-----' + questionNum);
        console.log(totalNum == questionNum);
        if (totalNum == questionNum) {
          that.questionOver();
        }
      }, 600)
    }else{
      that.audioErrorCtx.play();
      that.useLifeCard(curQuestionIndex, question);
    }
    clearTimeout(countTimer);
    that.setData({
      question: question
    })
  },
  useLifeCard: function (curQuestionIndex, question){
    var that = this;
    var question = that.data.question;
    var reviveCard = that.data.reviveCard;
    var allowCard = that.data.allowCard;
    if (allowCard > 0 && reviveCard>0){
      wx.showLoading({
        title: '加载中'
      })
      wx.request({
        url: app.globalData.requestUrl,
        data: {
          map: 'applet_subject_fetch_use_card'
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            var curIndex = curQuestionIndex-1;
            question[curIndex].chooseAnswer = question[curIndex].answer;
            reviveCard--;
            allowCard--;
            that.setData({
              isShowresult: true,
              modaltype: 1,
              reviveCard: reviveCard,
              allowCard: allowCard
            })
            var totalNum = question.length;
            var questionNum = 0;
            for (var i = 0; i < question.length; i++) {
              if (question[i].chooseAnswer != '') {
                questionNum++;
              }
            }
            console.log(totalNum + '-----' + questionNum);
            console.log(totalNum == questionNum);
            if (totalNum == questionNum) {
              that.setData({
                question: question
              })
              that.questionOver();
            }else{
              setTimeout(function () {
                if (curQuestionIndex < question.length) {
                  curQuestionIndex++;
                  that.getAudio();
                }
                that.setData({
                  curQuestionIndex: curQuestionIndex,
                  isShowresult: false,
                  question: question
                })
              }, 2000)
            }
          } else {
            // app.errorTip(that, res.data.em, 2000);
            var msg = '暂无可用复活卡，或者可用复活卡次数已用完';
            that.setData({
              isShowresult: true,
              modaltype: 3,
              failTiptxt: msg
            })
            that.questionOver();
          }
        },
        complete: function () {
          wx.hideLoading();
        }
      });
    }else{
      console.log("游戏结束");
      setTimeout(function(){
        var msg = '暂无可用复活卡，或者可用复活卡次数已用完';
        that.setData({
          isShowresult: true,
          modaltype: 3,
          failTiptxt: msg
        })
        that.questionOver();
      },1000)
    }
  },
  questionOver: function () {
    var that = this;
    var question = that.data.question;
    var uploadContent=[];
    for (let item of question){
      let content={};
      content.id=item.id;
      content.chooseAnswer = item.chooseAnswer;
      uploadContent.push(content);
    }
    var type = that.data.type ? that.data.type : '';
    var data = {
      map: 'applet_subject_upload_answer',
      list: uploadContent,
      type: type
    };
    console.log(data);
    wx.showLoading({
      title: '加载中'
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          setTimeout(function(){
            if (res.data.data.status==1){
              that.setData({
                isShowresult: true,
                modaltype: 2,
                questionResult: res.data.data,
                failTiptxt: res.data.data.msg,
                isQuestioning:false
              })
            }else{
              that.setData({
                isShowresult: true,
                failTiptxt: res.data.data.msg,
                modaltype: 3,
                isQuestioning: false
              })
            }
            console.log(that.data.modaltype);
          },1000)
        } else {
          that.setData({
            isShowresult: true,
            failTiptxt: res.data.em,
            modaltype:3,
            isQuestioning: false
          })
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  countTime:function(){
    var that = this;
    var remainTime = that.data.remainTime;
    var curQuestionIndex = that.data.curQuestionIndex;
    var question = that.data.question;
    if (remainTime>=1){
      if (remainTime == 1) {
        that.audioTimeCtx.pause();
        that.endAudioCtx.play();
      }
      remainTime--;
    }else{
      clearTimeout(countTimer);
      that.useLifeCard(curQuestionIndex, question);
      return;
    }
    countTimer = setTimeout(function(){
      that.setData({
        remainTime: remainTime
      })
      that.countTime()
    },1000);
  },
  hideModal:function(){
    this.setData({
      isShowresult:false
    })
  },
  backQuestionIndex:function(){
    wx.navigateBack({
      delta:1
    })
  },
  onUnload: function () {
    console.log("页面卸载");
    var that = this;
    clearTimeout(countTimer);
    if (that.data.isQuestioning){
      var question = that.data.question;
      var uploadContent = [];
      for (let item of question) {
        let content = {};
        content.id = item.id;
        content.chooseAnswer = item.chooseAnswer;
        uploadContent.push(content);
      }
      var data = {
        map: 'applet_subject_upload_answer',
        list: uploadContent
      };
      console.log(data);
      wx.request({
        url: app.globalData.requestUrl,
        data: data,
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            console.log("答题次数减");
            console.log(res.data.data);
          } else {

          }
        },
        complete: function () {
        }
      });
    }
  },
  onShareAppMessage: function () {
    var that = this;
    var questionShare = app.globalData.questionShare ? app.globalData.questionShare : '';
    var title = questionShare.shareTitle ? questionShare.shareTitle : '趣味答题';
    var cover = questionShare.shareCover ? questionShare.shareCover : 'http://tiandiantong.oss-cn-beijing.aliyuncs.com/images/share-poster.jpg';
    var from = that.data.from;
    var url = '/pages/questionIndex/questionIndex?enterfrom=share';
    if (from=='sub'){
      url = '/subpages/questionIndex/questionIndex?enterfrom=share';
    }
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_subject_fetch_use_card',
        type: 'fetch'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          app.errorTip(that, res.data.data.msg, 2000);
          console.log(res.data.data.msg);
          that.setData({
            reviveCard: res.data.data.num
          })
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {

      }
    });
    return {
      title: title,
      imageUrl: cover,
      path: url
    }
  },
})

